<?php
/**
 *
 * 下载
 *
 * @version        $Id: download.php 1 15:38 2010年7月8日Z tianya $
 * @package        DedeCMS.Site
 * @copyright      Copyright (c) 2007 - 2010, DesDev, Inc.
 * @license        http://help.dedecms.com/usersguide/license.html
 * @link           http://www.dedecms.com
 */
require_once(dirname(__FILE__)."/../include/common.inc.php");
require_once(DEDEINC."/channelunit.class.php");
require_once(DEDEINC.'/memberlogin.class.php');
$cfg_ml = new MemberLogin();

if(!isset($open)) $open = 0;

//读取链接列表

if($open==0)
{
	

    $aid = (isset($aid) && is_numeric($aid)) ? $aid : 0;
    if($aid==0) exit(' Request Error! ');

    $arcRow = GetOneArchive($aid);
    if($arcRow['aid']=='')
    {
        ShowMsg('无法获取未知文档的信息!','-1');
        exit();
    }
    extract($arcRow, EXTR_SKIP);

    $cu = new ChannelUnit($arcRow['channel'],$aid);
    if(!is_array($cu->ChannelFields))
    {
        ShowMsg('获取文档信息失败！','-1');
        exit();
    }

    $vname = '';
    foreach($cu->ChannelFields as $k=>$v)
    {
        if($v['type']=='softlinks'){ $vname=$k; break; }
    }
    $row = $dsql->GetOne("SELECT $vname FROM `".$cu->ChannelInfos['addtable']."` WHERE aid='$aid'");

    include_once(DEDEINC.'/taglib/channel/softlinks.lib.php');
    $ctag = '';
    $downlinks = ch_softlinks($row[$vname], $ctag, $cu, '', TRUE);
	
	$dow = $dsql->GetOne("SELECT softurl1,pan_baidu,pan_baidu_mima,needmoney FROM `".$cu->ChannelInfos['addtable']."` WHERE aid='$id' ");

	//print_r($dow);
    require_once(DEDETEMPLATE.'/default/dow-list.htm');
    exit();
}

/*------------------------
//提供素材给用户下载(旧模式)
function getSoft_old()
------------------------*/
else if($open==1)
{
    //更新下载次数
    $id = isset($id) && is_numeric($id) ? $id : 0;
    $link = base64_decode(urldecode($link));
    $hash = md5($link);
    $rs = $dsql->ExecuteNoneQuery2("UPDATE `#@__downloads` SET downloads = downloads + 1 WHERE hash='$hash' ");
    if($rs <= 0)
    {
        $query = " INSERT INTO `#@__downloads`(`hash`,`id`,`downloads`) VALUES('$hash','$id',1); ";
        $dsql->ExecNoneQuery($query);
    }
    header("location:$link");
    exit();
}
/*------------------------
//提供素材给用户下载(新模式)
function getSoft_new()
------------------------*/
else if($open==2)
{
    $id = intval($id);
    
    $download_res = $dsql->GetOne("SELECT count(DISTINCT aid) as count FROM `product_download` WHERE mid='$cfg_ml->M_ID' and download_date='".date("Y/m/d")."'");
    $rank = $dsql->GetOne("SELECT rank,is_year_vip FROM `#@__member` WHERE mid='$cfg_ml->M_ID'");
    $is_aid = $dsql->GetOne("SELECT * FROM `product_download` WHERE mid='$cfg_ml->M_ID' and aid = '$id'");
    if (!$is_aid) {
        if($rank['rank'] >= 20 && $download_res['count'] >= 30 && $rank['is_year_vip'] == 0){
            ShowMsg('VIP用户一天最多下载30次，请明天再来下载喔!','-1');
            exit();
        }elseif($rank['rank'] < 20  && $download_res['count'] >= 1){
            ShowMsg('普通用户一天最多下载1次，请明天再来下载喔!','-1');
            exit();
        }elseif($rank['rank'] >= 20 && $download_res['count'] >= 50 && $rank['is_year_vip'] == 1){
            ShowMsg('年费会员一天最多下载50次，请明天再来下载喔!','-1');
            exit();
        }else{
            $paid = $dsql->GetOne("SELECT * FROM `product_download` WHERE mid='$cfg_ml->M_ID' and aid = '$id' and download_date='".date("Y/m/d")."'");
            if(empty($paid)){
                $download_count = $download_res['count']+1;
                $dsql->ExecuteNoneQuery("insert into `product_download` (mid,aid,download_second,download_date) values ('".$cfg_ml->M_ID."','".$id."','".$download_count."','".date("Y/m/d")."')");
            }
        }
    }
    //获得附加表信息
    $row = $dsql->GetOne("SELECT ch.addtable,arc.mid FROM `#@__arctiny` arc LEFT JOIN `#@__channeltype` ch ON ch.id=arc.channel WHERE arc.id='$id' ");

    if(empty($row['addtable']))
    {
        ShowMsg('找不到所需要的素材资源！', 'javascript:;');
        exit();
    }
    $mid = $row['mid'];
    
    //读取连接列表、下载权限信息
    $row = $dsql->GetOne("SELECT softlinks,daccess,needmoney,softurl1,pan_baidu FROM `{$row['addtable']}` WHERE aid='$id' ");
	//print_r($row);
    if(empty($row['softurl1']) && empty($row['pan_baidu']))
    {
        ShowMsg('找不到所需要的素材资源！', 'javascript:;');
        exit();
    }
    $softconfig = $dsql->GetOne("SELECT * FROM `#@__softconfig` ");
    $needRank = $softconfig['dfrank'];
    $needMoney = $softconfig['dfywboy'];
    if($softconfig['argrange']==0)
    {
        $needRank = $row['daccess'];
        $needMoney = $row['needmoney'];
    }
    
    //分析连接列表
    require_once(DEDEINC.'/dedetag.class.php');
	if(empty($row['softurl1'])&&isset($row['pan_baidu']))
	{ 
		$softUrl = $row['pan_baidu'];
	}elseif(isset($row['softurl1'])&&empty($row['pan_baidu'])){
		$softUrl = $row['softurl1'];	
	}
    $islocal = 0;
    $dtp = new DedeTagParse();
    $dtp->LoadSource();
    // if( !is_array($dtp->CTags) )
    // {
        // $dtp->Clear();
        // ShowMsg('找不到所需要的素材资源！', 'javascript:;');
        // exit();
    // }
    foreach($dtp->CTags as $ctag)
    {
        if($ctag->GetName()=='link')
        {
            $link = trim($ctag->GetInnerText());
			
            // $islocal = $ctag->GetAtt('islocal');
            
			// //分析本地链接
            // if(!isset($firstLink) && $islocal==1) $firstLink = $link;
            // if($islocal==1 && $softconfig['islocal'] != 1) continue;
            
            // //支持http,迅雷下载,ftp,flashget
            // if(!preg_match("#^http:\/\/|^thunder:\/\/|^ftp:\/\/|^flashget:\/\/#i", $link))
            // {
                 // $link = $cfg_mainsite.$link;
            // }
             $dbhash = substr(md5($link), 0, 24);
             //if($uhash==$dbhash)
				$softUrl = $link;
        }
    }
    $dtp->Clear();
    if($softUrl=='' && $softconfig['ismoresite']==1 
    && $softconfig['moresitedo']==1 && trim($softconfig['sites'])!='' && isset($firstLink))
    {
        $firstLink = preg_replace("#http:\/\/([^\/]*)\/#i", '/', $firstLink);
        $softconfig['sites'] = preg_replace("#[\r\n]{1,}#", "\n", $softconfig['sites']);
        $sites = explode("\n", trim($softconfig['sites']));
        foreach($sites as $site)
        {
            if(trim($site)=='') continue;
            list($link, $serverName) = explode('|', $site);
            $link = trim( preg_replace("#\/$#", "", $link) ).$firstLink;
            $dbhash = substr(md5($link), 0, 24);
            if($uhash == $dbhash) $softUrl = $link;
        }
    }
    if( $softUrl == '' )
    {
        ShowMsg('找不到所需要的素材资源！', 'javascript:;');
        exit();
    }
    //-------------------------
    // 读取文档信息，判断权限
    //-------------------------
    $arcRow = GetOneArchive($id);
    if($arcRow['aid']=='')
    {
        ShowMsg('无法获取未知文档的信息!','-1');
        exit();
    }
    extract($arcRow, EXTR_SKIP);
	
    //处理需要下载权限的素材
    if($needRank>0 || $needMoney>0 )
    {
        $arclink = $arcurl;
        $arctitle = $title;
        $arcLinktitle = "<a href=\"{$arcurl}\"><u>".$arctitle."</u></a>";
        $pubdate = GetDateTimeMk($pubdate);
    
        //会员级别不足
        if(($needRank>1 && $cfg_ml->M_Rank < $needRank && $mid != $cfg_ml->M_ID && $cfg_ml->isAdmin!=1))
        {
            $dsql->Execute('me' , "SELECT * FROM `#@__arcrank` ");
            while($row = $dsql->GetObject('me'))
            {
                $memberTypes[$row->rank] = $row->membername;
            }
            $memberTypes[0] = "游客";
            $msgtitle = "你没有权限下载素材：{$arctitle}！";
            $moremsg = "这个素材需要 <font color='red'>".$memberTypes[$needRank]."</font> 才能下载，你目前是：<font color='red'>".$memberTypes[$cfg_ml->M_Rank]."</font> ！";
            require_once(DEDETEMPLATE.'/default/dow-msg.htm');
            exit();
        }

        //以下为正常情况，自动扣点数
		
		//如果文章需要金币，检查用户是否浏览过本文档
        else if($mid != $cfg_ml->M_ID && $cfg_ml->isAdmin!=1)
        {
            $sql = "SELECT aid,money FROM `#@__member_operation` WHERE buyid='ARCHIVE".$id."' AND mid='".$cfg_ml->M_ID."'";
            $row = $dsql->GetOne($sql);
            
			
			//获取会员等级折扣
			$dissql = "SELECT discount FROM `#@__arcrank` WHERE rank='".$cfg_ml->M_Rank."'";
            $disrow = $dsql->GetOne($dissql);
			
			$needMoney=$needMoney*$disrow['discount']/100;
			
			//未购买过此文章
            if( !is_array($row) )
            {
                //没有足够的金币
                if( $needMoney > $cfg_ml->M_Money || $cfg_ml->M_Money=='')
                {
                    $msgtitle = "你没有权限下载素材：{$arctitle}！";
                    $moremsg = "这个素材需要 <font color='red'>".$needMoney." 金币</font> 才能下载，你目前拥有金币：<font color='red'>".$cfg_ml->M_Money." 个</font> ！";
                    require_once(DEDETEMPLATE.'/default/dow-msg.htm');
                    exit(0);
                }
				
				$dsql->ExecuteNoneQuery("insert into #@__member_dows (mid,umid,aid,money,addtime) values ('".$cfg_ml->M_ID."','$mid','$id','-".$needMoney."','".time()."')");
				
				//更新下载次数
				$dsql->ExecuteNoneQuery2("UPDATE `#@__addonsoft` SET dows = dows + 1 WHERE aid='$id' ");
				$dsql->ExecuteNoneQuery2("UPDATE `#@__archives` SET dows = dows + 1 WHERE id='$aid' ");
				$hash = md5($softUrl);
				$rs = $dsql->ExecuteNoneQuery2("UPDATE `#@__downloads` SET downloads = downloads+1 WHERE hash='$hash' ");
				if($rs <= 0)
				{
					$query = " INSERT INTO `#@__downloads`(`hash`, `id`, `downloads`) VALUES('$hash', '$id', 1); ";
					$dsql->ExecNoneQuery($query);
				}
				
				//有足够金币，记录用户信息
				$u_m = $dsql->GetOne("SELECT b.qq,a.email FROM `#@__member` a, `#@__member_person` b WHERE a.mid=b.mid and  a.mid='".$mid."' ");
				$email=$u_m['email'];
				$qq=$u_m['qq'];				
				$needMoneys = "-$needMoney";
                $inquery = "INSERT INTO `#@__member_operation`(arcid,buyid,mid,oldinfo,money,mtime,product,pname,umid,sta,mai1,mai2,qq,email)
                  VALUES ('$id','ARCHIVE".$id."','".$cfg_ml->M_ID."','$arctitle','$needMoneys','".time()."','archive','买素材','$mid','2','".$cfg_ml->M_UserName."','$writer','$qq','$email'); ";
                //记录定单
                if( !$dsql->ExecuteNoneQuery($inquery) )
                {
                    ShowMsg('记录定单失败, 请返回', '-1');
                    exit(0);
                }
				
                //扣除金币
                $dsql->ExecuteNoneQuery("UPDATE `#@__member` SET money = money - $needMoney WHERE mid='".$cfg_ml->M_ID."'");
				
				$hash = md5($softUrl);
				$rs = $dsql->ExecuteNoneQuery2("UPDATE `#@__downloads` SET downloads = downloads+1 WHERE hash='$hash' ");
				if($rs <= 0)
				{
					$query = " INSERT INTO `#@__downloads`(`hash`, `id`, `downloads`) VALUES('$hash', '$id', 1); ";
					$dsql->ExecNoneQuery($query);
				}
				//资源被下载后发送邮件通知投稿者
				if($needMoney>0){			
					$arcRow = GetOneArchive($id);
					$url=$cfg_basehost;
					$u_info = $dsql->GetOne("SELECT uname,email,money FROM `#@__member` WHERE mid='".$arcRow['mid']."' ");
					$money=$u_info['money']+$needMoney;
					$email=$u_info['email'];
					$uname=$u_info['uname'];
					$title=$arcRow['title'];
					$arcurl=$url.$arcRow['arcurl'];
					
					$mailtitle = "{$uname},您在素材网发布的模板成功售出!";
					$mailbody = "<P>{$uname}：</P><P>恭喜您!</P><P>您发布的模板 <a href=\"{$arcurl}\" target=\"_blank\"><font style=\"color:red;\">{$title}</font></a> 成功售出!</P><P><a href=\"/user/operation.php\" target=\"_blank\"><font style=\"color:red;\">详细信息请点我查看。</font></a></P><P>该邮件由系统自动发送，请勿直接回复。</P><P>感谢您对素材网(sucai58.com)的支持!</P><P>素材网(<a href=\"{$url}\" target=\"_blank\">www.sucai58.com</a>)</P><P>客服QQ:12345678</P>";
					$headers = $cfg_adminemail;
					$mailtype = 'HTML';
					require_once(DEDEINC.'/mail.class.php');
					$smtp = new smtp($cfg_smtp_server,$cfg_smtp_port,true,$cfg_smtp_usermail,$cfg_smtp_password);
					$smtp->debug = false;
					$smtp->sendmail($email,$cfg_webname ,$cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
				}
				
				if($mid != $cfg_ml->M_ID)
				{
					
					$u_m = $dsql->GetOne("SELECT b.qq,a.email FROM `#@__member` a, `#@__member_person` b WHERE a.mid=b.mid and  a.mid='".$cfg_ml->M_ID."' ");
					$email=$u_m['email'];
					$qq=$u_m['qq'];
					
					//增加作者金币
					$y = $dsql->ExecuteNoneQuery2("UPDATE `#@__member` SET money = money + $needMoney WHERE mid='$mid' ");
					
					//更新作者作品售出次数
					$o = $dsql->ExecuteNoneQuery2("UPDATE `#@__member_tj` SET shouchu = shouchu + 1 WHERE mid='$mid' ");
					
					$needMoneys = "+$needMoney";
					$inquery = "INSERT INTO `#@__member_operation`(arcid,buyid,mid,oldinfo,money,mtime,product,pname,umid,sta,mai1,mai2,qq,email)
                  VALUES ('$id','ARCHIVE".$id."','".$mid."','$arctitle','$needMoneys','".time()."','shouyi','卖素材','$mid','2','".$cfg_ml->M_UserName."','$writer','$qq','$email'); ";
					//记录定单
					if( !$dsql->ExecuteNoneQuery($inquery) )
					{
						ShowMsg('收益订单记录失败, 请返回', '-1');
						exit(0);
					}
				}
            }
        }
    }
	else if($needMoney==0)
	{
		$sql = "SELECT aid,money FROM `#@__member_operation` WHERE buyid='ARCHIVE".$id."' AND mid='".$cfg_ml->M_ID."'";
        $row = $dsql->GetOne($sql);
		//未购买过此文章
        if( !is_array($row) )
        {
			$dsql->ExecuteNoneQuery("insert into #@__member_dows (mid,umid,aid,money,addtime) values ('".$cfg_ml->M_ID."','$mid','$id','-".$needMoney."','".time()."')");
			
			//有足够金币，记录用户信息
			$u_m = $dsql->GetOne("SELECT b.qq,a.email FROM `#@__member` a, `#@__member_person` b WHERE a.mid=b.mid and  a.mid='".$mid."' ");
			$email=$u_m['email'];
			$qq=$u_m['qq'];
			
			$needMoneys = "-$needMoney";
            $inquery = "INSERT INTO `#@__member_operation`(arcid,buyid,mid,oldinfo,money,mtime,product,pname,umid,sta,mai1,mai2,qq,email)
              VALUES ('$id','ARCHIVE".$id."','".$cfg_ml->M_ID."','$arctitle','$needMoneys','".time()."','archive','买素材','$mid','2','".$cfg_ml->M_UserName."','$writer','$qq','$email'); ";
            //记录定单
             if( !$dsql->ExecuteNoneQuery($inquery) )
             {
                 ShowMsg('记录定单失败, 请返回', '-1');
                 exit(0);
             }
			$zneedMoneys = "+$needMoney";
			$cinquery = "INSERT INTO `#@__member_operation`(arcid,buyid,mid,oldinfo,money,mtime,product,pname,umid,sta,mai1,mai2,qq,email)
                  VALUES ('$id','ARCHIVE".$id."','".$mid."','$arctitle','$zneedMoneys','".time()."','shouyi','卖素材','$mid','2','".$cfg_ml->M_UserName."','$writer','$qq','$email'); ";	
				  //记录定单
             if( !$dsql->ExecuteNoneQuery($cinquery) )
             {
                 ShowMsg('记录定单失败, 请返回', '-1');
                 exit(0);
             }
			//更新下载次数
			$dsql->ExecuteNoneQuery2("UPDATE `#@__addonsoft` SET dows = dows + 1 WHERE aid='$id' ");
			$dsql->ExecuteNoneQuery2("UPDATE `#@__archives` SET dows = dows + 1 WHERE id='$aid' ");
			$hash = md5($softUrl);
			$rs = $dsql->ExecuteNoneQuery2("UPDATE `#@__downloads` SET downloads = downloads+1 WHERE hash='$hash' ");
			if($rs <= 0)
			{
				$query = " INSERT INTO `#@__downloads`(`hash`, `id`, `downloads`) VALUES('$hash', '$id', 1); ";
				$dsql->ExecNoneQuery($query);
			}
        }
			
	}
    header("location:{$softUrl}");
    exit();
}//opentype=2